/*
 * Server.cpp
 *
 *  Created on: 1 mar 2010
 *      Author: hule
 */

#include "Server.h"

Server::Server(int port) {

	/* Open a listening socket */
	if (!(recv_socket = SDLNet_UDP_Open(port))) {
		cout<<"Receive Socket Error: "<<SDLNet_GetError()<<endl;
	}
	/* Open a sending socket */
	if (!(send_socket = SDLNet_UDP_Open(0))) {
		cout<<"Send Socket Error: "<<SDLNet_GetError()<<endl;
	}

	SDLNet_ResolveHost(&host, "", port);
	cout << host.host << " " << host.port << " " << endl;

	recv_packet = SDLNet_AllocPacket(512);
	send_packet = SDLNet_AllocPacket(512);

	cout << "Server succesfully created." << endl;
}


void Server::send(string mess, int user) {
	//cout << "Send:   " << mess << endl;
	const char *m;
	m = mess.c_str();

	send_packet->data = (Uint8*)m;
	send_packet->len = strlen((char *)send_packet->data) + 1;

	// Send to all
	if (user == -1) {
		for (int i=0; i<send_packets.size(); i++) {
			send_packet->address = send_packets[i];
			//send_packet->address.port = host.port;
			SDLNet_UDP_Send(send_socket, -1, send_packet);

		}
	}
	else {
		send_packet->address = send_packets[user];
		SDLNet_UDP_Send(send_socket, -1, send_packet);
		//
	}
	//cout << "Sent." << endl;

}

string Server::receive() {
	//cout << "Receive" << endl;

	if (SDLNet_UDP_Recv(recv_socket, recv_packet) != 0) {
		string ret;

		// Search for the user
		bool found = false;
		for (int i=0; i<send_packets.size(); i++) {
			if (recv_packet->address.host == send_packets[i].host) found = true;
		}
		if (!found) {
			// Add new user
			send_packets.push_back( recv_packet->address );
			cout << "New client " << recv_packet->address.host << " added" << endl;

			return "new";
		}

		ret = string( (char *)recv_packet->data );
		//cout<<"Received: "<< ret << endl;

		stringstream ss;
		ss << ret << ";" << recv_packet->address.host;

		return ss.str();
	}

	return "";

}

int Server::findUser(int host) {
	for (int i=0; i<send_packets.size(); i++) {
		if (host == send_packets[i].host) {
			return i;
		}
	}
	return -1;
}


